package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiClient extends Thread {
    private Socket client;

    public MultiClient(Socket c) {
        this.client = c;
    }

    public void run() {
        InputStream in = null;
        PrintWriter out = null;
        try {

            // Mutil User but can't parallel

            while (true) {
                System.out.println("start...");
                in = client.getInputStream();
                out = new PrintWriter(client.getOutputStream());

                byte[] receivBuf = new byte[4096];

                in.read(receivBuf);

                String str = new String(receivBuf, "utf-8").trim();

                System.out.println("###receivedData:" + str);

                String rs = "";
                str = str.replace("#OK*", "").trim();//去掉特殊字符
                while (str.length() >= 40) {
                    rs = ClockService.handResult(str.substring(0, 40));
                    str = str.substring(40);
                }
                out.write(rs);
                out.flush();
                try {
                    sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                System.out.println("===sendData:" + rs);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
            try {
                if (out != null) out.close();
                if (in != null) in.close();
                if (client != null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {

        }
    }

    public static void multiStart(int port) {
        try {
            ServerSocket server = new ServerSocket(port);
            while (true) {
                // transfer location change Single User or Multi User
                MultiClient mc = new MultiClient(server.accept());
                mc.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        int servPort = args.length > 0 ? Integer.parseInt(args[0]) : 2000;
        multiStart(servPort);
    }
}